﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Utils
{
    /// <summary>
    /// 异步工具类
    /// 代替async await语法糖
    /// </summary>
    public class Await
    {
        /// <summary>
        /// 状态
        /// </summary>
        private int _state { get; set; }

        /// <summary>
        /// 异步操作集合
        /// </summary>
        private List<Action> _actionList = new List<Action>();

        /// <summary>
        /// 操作结果集合
        /// </summary>
        private List<object> _resultList = new List<object>();

        /// <summary>
        /// 完成后的回调
        /// </summary>
        private Action<List<object>> _completedCallback;

        /// <summary>
        /// 是否已调用回调函数
        /// </summary>
        private bool _completedCalled = false;

        /// <summary>
        /// 锁
        /// </summary>
        private object _lock = new object();

        /// <summary>
        /// 异步工具类 构造函数
        /// </summary>
        public Await()
        {
            _state = 0;
        }

        /// <summary>
        /// 添加一个异步操作
        /// </summary>
        public Await Add(Action action)
        {
            _actionList.Add(action);
            return this;
        }

        /// <summary>
        /// 开始执行
        /// </summary>
        public Await Start()
        {
            foreach (Action action in _actionList)
            {
                action();
            }
            return this;
        }

        /// <summary>
        /// 收集结果
        /// </summary>
        public Await Collect(object result, out object outResult)
        {
            outResult = result;
            _resultList.Add(result);
            lock (_lock)
            {
                _state++;
                if (_state == _actionList.Count && _completedCallback != null && !_completedCalled)
                {
                    _completedCalled = true;
                    _completedCallback(_resultList);
                }
            }
            return this;
        }

        /// <summary>
        /// 注册完成后的回调函数
        /// </summary>
        public Await Completed(Action<List<object>> completedCallback)
        {
            this._completedCallback = completedCallback;
            return this;
        }
    }
}
